/**
 * Copyright (C) 2025 ROKAE (Beijing) Technology Co., LTD.
 * All Rights Reserved.
 *
 * Information in this file is the intellectual property of Rokae Technology Co., Ltd,
 * And may contains trade secrets that must be stored and viewed confidentially.
 *
 * @file StatusPoller.cpp
 * @brief 周期性查询设备状态的工具类
 */
#include "StatusPoller.h"

StatusPoller::StatusPoller(QObject *parent) : QObject(parent)
{
    m_is_init = false;
}

void StatusPoller::setDeviceId(int id)
{
    m_device_id = id;
}

void StatusPoller::setInit(bool status)
{
    m_is_init = status;
}

void StatusPoller::openTimer()
{
    m_timer->start();
}

void StatusPoller::closeTimer()
{
    m_timer->stop();
}

void StatusPoller::startPolling()
{
    m_timer = new QTimer(this);
    connect(m_timer, &QTimer::timeout, this, &StatusPoller::pollStatus);
    m_timer->start(200); // 200ms 周期
}

void StatusPoller::pollStatus()
{
    if (!m_is_init)
    {
        return;
    }

    QJsonObject status_obj;
    status_obj["slave_id"] = m_device_id;

    QJsonObject status_root;
    status_root["get_angle"] = status_obj;

    QJsonObject root;
    root["InspireRobotsPlugin"] = status_root;

    QJsonArray resJsonArray = xplugin::xPluginInterface().commandCustomData(this, root);

    if (resJsonArray.isEmpty())
    {
        return;
    }

    QJsonObject status = resJsonArray[0]
            .toObject()["InspireRobotsPlugin"]
            .toObject()["get_angle"]
            .toObject();

    emit statusUpdated(status);
}
